package com.wlstock.funi.ui;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.wlstock.funi.R;
import com.wlstock.funi.app.FundApplication;
import com.wlstock.funi.app.FundAsyTask;
import com.wlstock.funi.app.FundAsyTask.TaskLitener;
import com.wlstock.funi.app.FundAsyTask.TaskResultListener;
import com.wlstock.funi.model.PositionModel;
import com.wlstock.funi.runnable.CurPosition;
import com.wlstock.funi.runnable.RefreshLogSession;
import com.wlstock.funi.runnable.SysHisTrade;
import com.wlstock.funi.utils.HttpUtils;
import com.wlstock.funi.utils.IOUtils;
import com.wlstock.funi.utils.ToastUtils;

public class LoginActvity extends FundBaseActivity implements OnClickListener, RefreshLogSession.ResultListener, CurPosition.CurPositionListener {
	public static final String TAG = "TESTCASE";
	private ImageView codeImg;
	private EditText codEditTV;
	
	private Button btn_log;
	private Button btn_refresh;
	private EditText accountEditTV;
	private EditText passwordEditTV;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.activity_login);
		btn_log = (Button) findViewById(R.id.btn_log);
		btn_log.setOnClickListener(this);
		btn_refresh = (Button) findViewById(R.id.btn_refresh);
		btn_refresh.setOnClickListener(this);
		
		codeImg = (ImageView) findViewById(R.id.codeImg);
		codEditTV = (EditText) findViewById(R.id.codEditTV);
		accountEditTV = (EditText) findViewById(R.id.accountEditTV);
		passwordEditTV = (EditText) findViewById(R.id.passwordEditTV);
		
		accountEditTV.setText(getString(R.string.c1) + getString(R.string.d1));
		
		getCookie();
	}
	
	public void getCookie() {
		
			FundAsyTask<Void, Void, HttpResponse> cookieTask = new FundAsyTask<Void, Void, HttpResponse>();
			cookieTask.backListener = new TaskLitener<Void,HttpResponse>() {
				@Override
				public HttpResponse doInBackground(Void... params) {
					HttpGet requestGet = new HttpGet(getString(R.string.loginURL));
					requestGet.addHeader("Connection", "keep-alive");
					requestGet.addHeader("Cache-Control", "max-age=0");
					requestGet.addHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
					requestGet.addHeader("Referer","https://etrade.cs.ecitic.com/ymtrade/login/login.jsp");
					requestGet.addHeader("Accept-Encoding", "gzip, deflate, sdch");
					requestGet.addHeader("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6");
					HttpClient client = new DefaultHttpClient();
					try {
						HttpResponse response = client.execute(requestGet);
						return response;
					} catch (ClientProtocolException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					return null;
				};
			};
			
			cookieTask.resultListener = new TaskResultListener<HttpResponse>() {
				@Override
				public void onPostResult(HttpResponse result) {
					// TODO Auto-generated method stub
					if (result.getStatusLine().getStatusCode() == 200) {
						if (HttpUtils.setCookie(result)!=null) {
							FundApplication.cookie = HttpUtils.setCookie(result);
						}
						if (!FundApplication.cookie.isEmpty()) {
							refreshCodeImg();
							btn_log.setEnabled(true);
							btn_refresh.setEnabled(true);
						}
					}
				}
			};
			cookieTask.execute();
	}

	private void refreshCodeImg() {
		
//			Accept:image/webp,image/*,*/*;q=0.8
//			Accept-Encoding:gzip, deflate, sdch
//			Accept-Language:zh-CN,zh;q=0.8,en;q=0.6
//			Connection:keep-alive
//			Cookie:JSESSIONID=sZBDWcYV6MDW1ZnG5kXDJCHkJ2khZmJSXN1GPyknQdST2fmQvs1T!1036719599!-1780973960; ssl=etrade-ssl-2
//			Host:etrade.cs.ecitic.com
//			Referer:https://etrade.cs.ecitic.com/ymtrade/login/login.jsp?ssl=false&ftype=pro
//			User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36
			
			FundAsyTask<Void, Void, byte[]> codeImgTask = new FundAsyTask<Void, Void, byte[]>();
			codeImgTask.backListener = new TaskLitener<Void, byte[]>() {

				@Override
				public byte[] doInBackground(Void... params) {
					// TODO Auto-generated method stub
					DefaultHttpClient client = new DefaultHttpClient();
					double random = Math.random();
					HttpGet erCodeGet = new HttpGet(getString(R.string.kaptChaURL)+random);
					erCodeGet.addHeader("Accept", "image/webp,image/*,*/*;q=0.8");
					erCodeGet.addHeader("Accept-Encoding", "gzip, deflate, sdch");
					erCodeGet.addHeader("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6");
					erCodeGet.addHeader("Connection", "keep-alive");
					erCodeGet.addHeader("Referer", getString(R.string.loginURL));
					erCodeGet.addHeader("Cookie",FundApplication.cookie);
					
					try {
						HttpResponse erCodeResponse = client.execute(erCodeGet);
						if (erCodeResponse.getStatusLine().getStatusCode() == 200) {
							if (HttpUtils.setCookie(erCodeResponse)!=null) {
								FundApplication.cookie = HttpUtils.setCookie(erCodeResponse);
							}
							InputStream is = erCodeResponse.getEntity().getContent();
							byte[] bytes = new byte[1024];
							ByteArrayOutputStream bos = new ByteArrayOutputStream();
							int count = 0;
							while ((count = is.read(bytes)) != -1) {
								bos.write(bytes, 0, count);
							}
							byte[] byteArray = bos.toByteArray();
							return byteArray;
						}
					} catch (ClientProtocolException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} finally{
						client.getConnectionManager().shutdown();
					}
					return null;
				}
			};
			
			codeImgTask.resultListener = new TaskResultListener<byte[]>() {

				@Override
				public void onPostResult(byte[] result) {
					// TODO Auto-generated method stub
					if (result!=null) {
						Bitmap bitmap = BitmapFactory.decodeByteArray(result, 0, result.length);
						codeImg.setImageBitmap(bitmap);	
					}
				}
			};
			codeImgTask.execute();
	
	}
	
	
	private void login(){
		if ("".equals(this.accountEditTV.getText().toString())||"".equals(this.passwordEditTV.getText().toString())) {
			Toast.makeText(this, "账号或密码不能为空", 500).show();
		}
		if ("".equals(this.codEditTV.getText().toString())) {
			Toast.makeText(this, "验证码不能为空", 500).show();
		}
//		orgid=&orgname=&inputtype=Z&inputid=880000910112&trdpwd=520111&mac=&vcode=a34d&ftype=pro&pwdtype=&cainfo=&hardinfo=
		HashMap<String, String> params = new HashMap<String, String>();
		params.put("orgid", "");
		params.put("orgname", "");
		params.put("inputtype", "Z");
		params.put("inputid", this.accountEditTV.getText().toString());
		params.put("trdpwd", this.passwordEditTV.getText().toString());
		params.put("mac", "");
		params.put("vcode", this.codEditTV.getText().toString());
		params.put("ftype", "");
		params.put("pwdtype", "");
		params.put("cainfo", "");
		params.put("hardinfo", "");
		List<NameValuePair> valuePairs = HttpUtils.getParms(params);

		// Accept:application/json, text/javascript, */*
		// Accept-Encoding:gzip, deflate
		// Accept-Language:zh-CN,zh;q=0.8,en;q=0.6
		// Connection:keep-alive
		// Content-Length:115
		// Content-Type:application/x-www-form-urlencoded
		// Cookie:JSESSIONID=GkGXWdnLT2DNxk2TCXybFzQhnxxMnyFj0tpL135hZgV1btwJ08P7!-1765034196!1149879797;
		// ssl=etrade-ssl-1
		// Host:etrade.cs.ecitic.com
		// Origin:https://etrade.cs.ecitic.com
		// Referer:https://etrade.cs.ecitic.com/ymtrade/login/login.jsp?ssl=false&ftype=pro
		// User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36
		// (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36
		// X-Requested-With:XMLHttpRequest
		FundAsyTask<List<NameValuePair>, Void, HttpResponse> loginTask = new FundAsyTask<List<NameValuePair>, Void, HttpResponse>();
		loginTask.backListener = new TaskLitener<List<NameValuePair>, HttpResponse>() {

			@Override
			public HttpResponse doInBackground(List<NameValuePair>... params) {
				// TODO Auto-generated method stub
				DefaultHttpClient client = new DefaultHttpClient();
				try {
					UrlEncodedFormEntity encodedFormEntity = new UrlEncodedFormEntity(params[0]);
					HttpPost post = new HttpPost(getString(R.string.loginActionURL));
					post.setEntity(encodedFormEntity);
					post.addHeader("Accept","application/json, text/javascript, */*");
					post.addHeader("Accept-Encoding", "gzip, deflate");
					post.addHeader("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6");
					post.addHeader("Connection", "keep-alive");
					post.addHeader("Content-Type","application/x-www-form-urlencoded");
					post.addHeader("Cookie", FundApplication.cookie);
					post.addHeader("Referer", getString(R.string.loginURL));
					post.addHeader("X-Requested-With", "XMLHttpRequest");
					post.addHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36");
					return client.execute(post);
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ClientProtocolException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} finally {
					client.getConnectionManager().shutdown();
				}
				return null;
			}
		};

		loginTask.resultListener = new TaskResultListener<HttpResponse>() {

			@Override
			public void onPostResult(HttpResponse response) {
				// TODO Auto-generated method stub
				try {
					if (response!=null && response.getStatusLine().getStatusCode() == 200) {
						if (HttpUtils.setCookie(response) != null) {
							FundApplication.cookie = HttpUtils.setCookie(response);
						}
						String result = IOUtils.is2Str(response.getEntity().getContent());
						// {cssweb_type:'error',cssweb_msg:'验证码错误'}
						// {cssweb_type:'success'}
						if (result.trim().equals("")) {
							Toast.makeText(LoginActvity.this, "网络繁忙，请稍后重试",1000).show();
							refreshCodeImg();
						} else {
							JSONObject obj = new JSONObject(result);
							String cssweb_type = obj.getString("cssweb_type");
							if (cssweb_type.equalsIgnoreCase("success")) {
								RefreshLogSession.getInstance().refresh(LoginActvity.this);

								Toast.makeText(LoginActvity.this,R.string.login_success, 1000).show();
								FundApplication.isLogSuccess = true;


								LoginActvity.this.finish();
							} else {
								String cssweb_msg = obj.getString("cssweb_msg");
								Toast.makeText(LoginActvity.this,R.string.login_faile + ":" + cssweb_msg,1000).show();
								refreshCodeImg();
							}
						}
						Log.i(TAG, result);
					}
				} catch (JSONException e) {
					// TODO: handle exception
				} catch (IllegalStateException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		};
		loginTask.execute(valuePairs);
	}
	
	
	
	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		switch (arg0.getId()) {
		case R.id.btn_log:
			login();
			break;
		case R.id.btn_refresh:
			refreshCodeImg();
			break;
		default:
			break;
		}
	}

	@Override
	public void resultSuccess() {

		reqCurPosition();

	}

	@Override
	public void resultFaile() {
		ToastUtils.showMiddleMsg(this,"刷新持股信息失败,无法同步持仓信息");

		reqCurPosition();
	}

	private void reqCurPosition() {
		CurPosition reqPostion = new CurPosition();
		reqPostion.requset(LoginActvity.this);
	}

	@Override
	public void getPosition(PositionModel model) {
		ToastUtils.showMiddleMsg(this,"刷新持仓信息成功");
		SysHisTrade sysHisTrade = new SysHisTrade();
		sysHisTrade.request();
	}
}
